package cn.tangsihai.quartz.job;

import cn.tangsihai.basic.exception.MyException;
import cn.tangsihai.order.domain.OrderPet;
import cn.tangsihai.order.domain.OrderPetDetail;
import cn.tangsihai.order.mapper.OrderPetDetailMapper;
import cn.tangsihai.order.mapper.OrderPetMapper;
import cn.tangsihai.pay.domain.PayBill;
import cn.tangsihai.pay.mapper.PayBillMapper;
import cn.tangsihai.pet.domain.Pet;
import cn.tangsihai.pet.mapper.PetMapper;
import cn.tangsihai.quartz.util.QuartzUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.common.models.AlipayTradeCloseResponse;
import com.sun.org.apache.xpath.internal.SourceTree;
import lombok.SneakyThrows;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sound.midi.Soundbank;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时器工具类
 */
@Component
public class OrderOverTimeJob implements Job {
    @Autowired
    private OrderPetMapper orderPetMapper;
    @Autowired
    private PayBillMapper payBillMapper;
    @Autowired
    private OrderPetDetailMapper orderPetDetailMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private Scheduler scheduler;

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap dataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        Map<String, String> map = (Map<String, String>) dataMap.get("params");
        String orderSn = map.get("orderSn");
        String jobName = map.get("jobName");
        // 根据订单号查询支付单数据
        PayBill payBill = payBillMapper.findByOrderSn(orderSn);
        // 根据订单号查询业务单数据
        OrderPet orderPet = orderPetMapper.findByOrderSn(orderSn);
        if (payBill == null || orderPet == null){
            System.out.println("数据错误");
            // 删除定时任务
            QuartzUtil.removeJob(scheduler, jobName);
            return;
        }
        // 如果状态是待支付，修改为超时
        if (payBill.getState() == 0){
            payBill.setState(PayBill.PAYTYPE_FAIL_PAY);
        }
        if (orderPet.getState() == 0) {
            orderPet.setState(OrderPet.ORDER_OVERTIME_FAIL);
        }

        // 库存回存
        List<OrderPetDetail> orderPetDetails = orderPetDetailMapper.batchFindByOrderSn(orderSn);
        List<Long> ids = orderPetDetails.stream().map(petdetail -> petdetail.getPetId()).collect(Collectors.toList());
        List<Pet> pets = petMapper.batchFindById(ids);
        pets.forEach(pet -> {
            pet.setRepertory(pet.getRepertory() + 1);
        });

        // 调用支付宝关单接口
        AlipayTradeCloseResponse close = Factory.Payment.Common().close(orderSn);
        QuartzUtil.removeJob(scheduler, jobName);
    }
}
